package com.flower.ApiGateway.untils;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.apache.commons.io.IOUtils;

/**
 * 解决Request内容只能读取一次的问题，新建一个类来缓存

 */
public class MAPIHttpServletRequestWrapper extends HttpServletRequestWrapper {

	private byte[] body; // 报文  
	
	public MAPIHttpServletRequestWrapper(HttpServletRequest request) {
		super(request);  
        try {
			body = IOUtils.toByteArray(request.getInputStream());
		} catch (IOException e) {
			e.printStackTrace();
		} 
	}
	
	@Override
	public BufferedReader getReader() throws IOException {
		return new BufferedReader(new InputStreamReader(getInputStream()));  
	}
	
	@Override
	public ServletInputStream getInputStream() throws IOException {
		final ByteArrayInputStream bais = new ByteArrayInputStream(body);  
        return new ServletInputStream() {  
              
            @Override  
            public int read() throws IOException {  
                return bais.read();  
            }

			@Override
			public boolean isFinished() {
				// TODO Auto-generated method stub
				return false;
			}

			@Override
			public boolean isReady() {
				// TODO Auto-generated method stub
				return false;
			}

			@Override
			public void setReadListener(ReadListener arg0) {
				// TODO Auto-generated method stub
				
			}  
        };  
	}

}
